import {Component} from '@angular/core';
import {IonicPage} from 'ionic-angular';

import {Router} from "@angular/router";
// 引入localstorage服务
import {LocalstorageProvider} from '../../providers/localstorage/localstorage'
import {HttphandleProvider} from '../../providers/httphandle/httphandle'
import { Response } from '@angular/http';

//  引入toast插件
import {ToastController} from 'ionic-angular';
import {Tools} from '../../tools/tools';
import {NativePageTransitions} from '@ionic-native/native-page-transitions';
import {Network} from '@ionic-native/network';

@IonicPage()
@Component({
  selector: 'page-login',
  templateUrl: 'login.html'
})
export class LoginPage extends Tools {

  private user: any;
  private existsubdomain: boolean = false;
  // private subdomainshow: string;
  private placeholderName: string = "请输入用户名@工厂子域名";
  private inputIconState: boolean = false;
  private inputListState: boolean = false;
  private inputListData: any;
  private loginData: any;
  private loginDataState: boolean = false;
  private loginState: boolean = false;
  private enableLogin: boolean = true;

  constructor(protected route: Router,
              private loc: LocalstorageProvider,
              private http: HttphandleProvider,
              private toastCtrl: ToastController,
              protected nativePageTransitions: NativePageTransitions,
              protected network: Network) {
    super(route, nativePageTransitions, network)
    this.user = {
      username: '',
      password: '',
      handledusername: []
    };
    this.inputListData = [];
    // 判断是否存在有效的token
    if (this.loc.get('token') && this.loc.get('subdomain') && this.loc.get('account')) {
      this.goback()
    }

    // 判断是否存在子域名
    // if (this.loc.get('subdomain')) {
    //   this.subdomainshow = '@' + this.loc.get('subdomain')
    //   this.existsubdomain = true;
    //   this.placeholderName = "请输入用户名"
    // } else {
    //   this.existsubdomain = false;
    this.placeholderName = "请输入用户名@工厂子域名";
    // }

    // 用户名
    // 12:111 ,121:111,2018:123

    if (this.getlocalstorage('loginData')) {
      this.loginDataState = true;
      this.loginData = this.getlocalstorage('loginData');
      this.user = {
        username: this.loginData.username,
        password: this.loginData.password,
      };
      if (this.user.username.indexOf('@') > 0) {
        this.user.handledusername = this.user.username.split('@');
        this.loc.set('subdomain', this.user.handledusername[1])
      }
    }

    if (this.getlocalstorage('inputList')) {
      if (this.getlocalstorage('inputList').length > 5) {
        let inputList = this.getlocalstorage('inputList');
        inputList.shift();
        this.loc.set('inputList', inputList);
      }
      this.inputListData = this.getlocalstorage('inputList');
    }

  }

  getlocalstorage(name: string) {
    let getstr = localStorage.getItem(name)
    if (getstr) {
      let o = JSON.parse(getstr);
      return o.value
    }
  }

  /**
   * 更换子域名信息，清空子域名存储
   */
  clearsubdomain() {
    this.existsubdomain = false;
    this.placeholderName = "请输入用户名@工厂子域名"
    this.loc.set('subdomain', '')
  }

  listChange(e) {
    //获取点击数据
    this.user.username = e.username;
    this.user.password = e.password;
    this.inputListState = false;
    this.splituserdata();
  }


  singleClear(index, listData) {
    if (listData.username == this.loginData.username) {
      this.user = {
        username: '',
        password: ''
      };
      this.inputListData.splice(index, 1);
      this.loc.set('inputList', this.inputListData);
      if(this.inputListData.length !==0){
        this.loc.set('loginData', this.inputListData[0])
      }
    } else {
      this.inputListData.splice(index, 1);
      this.loc.set('inputList', this.inputListData);
    }
  }


  hideListPage() {
    this.inputListState = false;
  }

  /**
   * 将用户输入的信息进行拆分
   * @Author mengxiaofei
   * @Date   2017-12-20T11:19:43+0800
   */
  splituserdata() {
    if (this.user.username) {
      if (this.user.username.indexOf('@') > 0) {
        this.user.handledusername = this.user.username.split('@');
        if (this.user.handledusername[1]) {
          this.loc.set('subdomain', this.user.handledusername[1])
        }
      }
    }

    if (this.user.username == "") {
      this.user.password = ""
    }
  }

  changeIcon(e) {
    //判断清除icon显示隐藏
    if (this.user.username !== '') {
      this.inputIconState = true;
    } else {
      this.inputIconState = false;
    }
    if (this.getlocalstorage('inputList')) {
      this.inputListData = this.getlocalstorage('inputList');
    }
    if (this.inputListData.length !== 0) {
      if (e && e.trim() != '') {
        this.inputListData = this.inputListData.filter((item) => {
          return (item.username.toLowerCase().indexOf(e.toLowerCase()) > -1);
        })
      } else {
        this.inputListData = this.getlocalstorage('inputList');
      }
    }
  }

  clearName() {
    //清空填写的用户名
    this.user.username = '';
    this.inputIconState = false;
  }


  focusState() {
    //获取输入框焦点
    if (this.inputListData.length !== 0) {
      this.inputListState = true;
    }
  }

  clearClick() {
    this.inputListData = [];
    this.loc.remove('inputList');
    this.inputListState = false;
  }

  repeatArr(arr) {
    var result = [], hash = {};
    for (var i = 0, elem, elem2; (elem = arr[i]) != null; i++) {
      elem = arr[i].username;
      elem2 = arr[i].password
      if (!hash[elem]) {
        result.push({username: elem, password: elem2});
        hash[elem] = true;
      }
    }
    this.loginData = {
      username: this.user.username,
      password: this.user.password,
    };
    this.loc.set('loginData', this.loginData);
    return result;
  }


  /**
   * 检测用户的输入是否合法
   * @return boolean
   */
  checkvalid() {
    var result: boolean;
    if (this.user.username.indexOf('@') > 0) {
      if (!this.user.handledusername[0] || !this.user.password) {
        result = false;
      } else if (!this.user.handledusername[1]) {
        result = false;
      } else {
        result = true
      }
    } else {
      result = false;
    }
    return result;
  }

  requestGetToken() {
    if (!this.checkvalid()) {
      // console.log(!this.user.username, !this.user.password)
      if (!this.user.username || !this.user.password) {
        this.toastCtrl.create({
          message: '请输入用户名和密码',
          position: 'top',
          duration: 1000
        }).present();
      } else {
        this.toastCtrl.create({
          message: '请输入所属工厂子域名',
          position: 'top',
          duration: 1000
        }).present();
      }
      return false;
    }
    // 发起获取token的请求
    this.loc.set('account', {
      username: this.user.handledusername[0],
      password: this.user.password
    })
    this.enableLogin = false
    this.loginState = false;
    this.http.getToken(res => {
      console.log('获取tokensuccess',res)
      this.loc.set('token', res.json())
      this.toastCtrl.create({
        message: '登录成功',
        position: 'top',
        duration: 1000
      }).present();
      this.enableLogin = true
      if (this.getlocalstorage('inputList')) {
        this.inputListData = this.getlocalstorage('inputList');
      }

      this.inputListData.unshift({username: this.user.username, password: this.user.password});

      this.loc.set('inputList', this.inputListData);
      let InputListData = this.inputListData;

      var datasList = this.repeatArr(InputListData);

      if (datasList.length > 5) {
        datasList.pop()
      }

      this.loc.set('inputList', datasList);

      this.goback()
    }, err => {
      console.log('获取token err',err)
      this.enableLogin = true
      if (err.status == 405 || err.type == 3) {
        this.toastCtrl.create({
          message: "工厂子域名不正确",
          position: 'top',
          duration: 2000
        }).present();
      } else if (err.status == 502) {
        this.toastCtrl.create({
          message: err.status,
          position: 'top',
          duration: 2000
        }).present();
      } else {
        var handleerr
        if (err instanceof Response) {
          handleerr = err.json()
        } else {
          handleerr = err
        }
        if (handleerr.error == "invalid_grant") {
          // this.toastCtrl.create({
          //   message: "用户名或密码错误，请重新输入",
          //   position: 'top',
          //   duration: 2000
          // }).present();
          this.loginState = true;
        } else if (handleerr.name == "TimeoutError") {
          this.toastCtrl.create({
            message: "请求超时",
            position: 'top',
            duration: 2000
          }).present();
        } else if (handleerr.name == 'network') {
          this.toastCtrl.create({
            message: err.message,
            position: 'top',
            duration: 2000
          }).present();
        } else if (handleerr.status == 500) {
          this.toastCtrl.create({
            message: "服务器错误",
            position: 'top',
            duration: 2000
          }).present();
        }
      }
    })
  }

}
